import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request,response,user):
    # 1,获取cookie
    cart_cookie = request.COOKIES.get('cart_cookie')

    # 2,判断cookie是否存在
    if cart_cookie is None:
        # 3,不存在返回
        return response

    # 4,解密cookie
    cart = pickle.loads(base64.b64decode(cart_cookie))

    # 5,判断解密后的值是否为空
    if cart is None:
        # 6,为空返回
        return response
    # 7,数据拆分
    # 8,拆分为hash类型    字典
    data = {}
    # 9,拆分集合    列表
    data_list = []     #保存选中状态的sku_id
    data_list_none = []   #保存未选中状态的sku_id

    for sku_id,data_dict in cart.items():
        data[sku_id]=data_dict['count']
        if data_dict['selected']:
            data_list.append(sku_id)
        else:
            data_list_none.append(sku_id)

    # 10,建立redis连接对象
    conn = get_redis_connection('cart')

    # 11,写入hash类型
    conn.hmset('cart_%s'%user.id,data)

    # 12,写入集合
    if data_list:
        conn.sadd('cart_selected_%s'%user.id,*data_list)
    if data_list_none:
        conn.srem('cart_selected_%s'%user.id,*data_list_none)

    # 13,删除cookie
    response.delete_cookie('cart_cookie')

    # 14,返回结果
    return response



